package com.example.litterpainterdemo.data

import android.app.Application
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.litterpainterdemo.R
import com.example.litterpainterdemo.db.Picture
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PictureViewModel(application: Application) :AndroidViewModel(application){
    private val repository = Repository()
    val pictures = repository.loadData()



    //写入数据
    fun insertData(picture: Picture){
        Log.v("wjb","savePicture之前: ${pictures.value!!.size}")
        viewModelScope.launch(Dispatchers.IO) {
            repository.insertData(picture)
            Log.v("wjb","savePicture之后: ${pictures.value!!.size}")
        }
    }

    //更新数据
    fun updateData(picture: Picture){
        Log.v("wjb","updateData之前: ${pictures.value!!.size}")
        viewModelScope.launch (Dispatchers.IO){
            repository.updateData(picture)
            Log.v("wjb","updateData之后: ${pictures.value!!.size}")
        }
    }

    fun deletePicture(index:Int){
        viewModelScope.launch (Dispatchers.IO){
            val picture = pictures.value?.get(index)
            if (picture != null) {
                repository.deleteData(picture)
            }
        }
    }
    //加载假数据
/*    fun fakeData(){
        val pictureList = listOf(
            Picture(0,"","", R.drawable.f1),
            Picture(0,"","", R.drawable.f2),
            Picture(0,"","", R.drawable.f3),
            Picture(0,"","", R.drawable.f4),
            Picture(0,"","", R.drawable.f1),
            Picture(0,"","", R.drawable.f2),
            Picture(0,"","", R.drawable.f3),
            Picture(0,"","", R.drawable.f4),
            Picture(0,"","", R.drawable.f1),
            Picture(0,"","", R.drawable.f2),
        )
        pictures.postValue(pictureList)
    }*/



}